package EventLoopTest.Test003;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class EventLoopGroupExample {
    public static void main(String[] args) {
        // 创建 EventLoopGroup
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);   // 接受连接
        EventLoopGroup workerGroup = new NioEventLoopGroup(4); // 处理IO

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                         protected void initChannel(SocketChannel ch) {
                             // Channel 会自动分配到 workerGroup 中的一个 EventLoop
                             System.out.println("Channel 分配到: " + ch.eventLoop());
                         }
                     });
            
            ChannelFuture future = bootstrap.bind(8888).sync();
            future.channel().closeFuture().sync();
            
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 优雅关停
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}